#!/usr/bin/env bash
# encoding: utf-8
# Desc: logstash 服务管理脚本
# 



if [[ $# -lt 2 ]]
then
  echo -e "args is wrong"
  echo -e "Usage: bash /opt/scripts/logstash-ctl.sh item_name [start|stop|status]"
  exit 1
fi

item_name=$1
ctl_string=$2

EXEC=/opt/app/logstash/bin/logstash
DATADIR="/opt/app/logstash/data/${item_name}/"
LOGDIR="/opt/app/logstash/logs/${item_name}/"
CONF="/opt/app/logstash/config/${item_name}.conf"
EXTRA_OPTS="-b 2000 -u 500"

items=("logstash-verify-book-log")

JVM_OPTS=“2G”


case $ctl_string in
    start)
      [ -d "${DATADIR}" ] || mkdir -p ${DATADIR}
      [ -d "${LOGDIR}" ]  || mkdir -p ${LOGDIR}
      sed -i "s/-Xms.*/-Xms${JVM_OPTS}/g" /opt/app/logstash/config/jvm.options
      sed -i "s/-Xmx.*/-Xmx${JVM_OPTS}/g" /opt/app/logstash/config/jvm.options
      PID=`ps -ef |grep logstash |grep ${CONF} |grep -v grep |awk '{print $2}' |xargs`
      if [[ -z ${PID} ]]
      then
        ${EXEC} --path.data ${DATADIR} -l ${LOGDIR} -f ${CONF} ${EXTRA_OPTS} &>/dev/null &
      else
        echo "${item_name} is already running now,please don't start it again."
      fi
    ;;
    stop)
      PID=`ps -ef |grep logstash |grep ${CONF} |grep -v grep |awk '{print $2}' |xargs`
      if [[ -z ${PID} ]]
      then
        echo "${item_name} is not running now."
      else
        kill ${PID}
        while true
        do
          sleep 5
          PID=`ps -ef |grep logstash |grep ${CONF} |grep -v grep |awk '{print $2}' |xargs`
          if [[ -z ${PID} ]]
          then
            echo "Done!"
            exit 0
          else
            kill ${PID}
            echo "killing,please waiting..."
          fi
        done
      fi
    ;;
    status)
      PID=`ps -ef |grep logstash |grep ${CONF} |grep -v grep |awk '{print $2}' |xargs`
      if [[ -z ${PID} ]]
      then
        echo "${item_name} is not running now."
      else
        echo "${item_name} is already running now,please don't start it again."
      fi
    ;;
    *)
      echo -e "Usage: bash /opt/scripts/logstash-ctl.sh item_name [start|stop|status]"
    ;;
esac